﻿using AutoUpdate.util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoUpdate
{
    public partial class CheckFrm : Form
    {
        String relseaseXmlFileName = "ReleaseList.xml";
        String customerNo;
        String systemNo;
        String appPath;
        String serverFileDir;
        String updDir;
        public String currentVersion;
        long totalSize = 0;
        XMLUtil xmlUtilLocal;
        XMLUtil xmlUtilDown;
        Thread trd;

        public CheckFrm(String customerNo, String systemNo)
        {
            InitializeComponent();
            //应用参数
            this.customerNo = customerNo;
            this.systemNo = systemNo;
            //应用程序目录
            this.appPath = Application.StartupPath;

            //测试时要把下面这句屏蔽,正式放开
            getLastestVersion();
        }

        public string getLastestVersion()
        {
            //定义返回新版本值
            String retVersion = "";
            
            //定义本地更新目录
            updDir = appPath + "\\upd";
            if (Directory.Exists(updDir))
            {
                Directory.Delete(updDir,true);
            }

            //读取本地更新配置文件
            xmlUtilLocal = new XMLUtil(appPath + "\\"+ relseaseXmlFileName);

            //下载远程更新说明文件到本地upd目录下
            //远程文件目录
            serverFileDir = xmlUtilLocal.serverURL + customerNo + "/" + systemNo + "/";

            if (!DownLoadUtil.DownloadFile(updDir, serverFileDir, relseaseXmlFileName))
            {
                return retVersion;   
            }

            //判断配置文件是否下载下来
            string fileDownLoad = updDir + "\\"+ relseaseXmlFileName;
            if (File.Exists(fileDownLoad))
            {
                xmlUtilDown = new XMLUtil(fileDownLoad);

                //进行版本对比
                string localVersion = xmlUtilLocal.releaseVersion;
                string downLoadVersion = xmlUtilDown.releaseVersion;

                if (downLoadVersion.CompareTo(localVersion) > 0)
                {
                    retVersion = downLoadVersion;
                }
            }
            currentVersion = retVersion;

            return retVersion;
        }

        private void CheckFrm_Load(object sender, EventArgs e)
        {
            showInfo();
        }

        public void showInfo()
        {
            lbinfo.Text = "新版本："+currentVersion+ "  发布时间：" + xmlUtilDown.releaseDate+"";
            foreach (String str in xmlUtilDown.desList)
            {
                listDesc.Items.Add(str);      
            }

            //计算下载文件总大小
            foreach (string str in xmlUtilDown.releaseFileList)
            {
                string[] arr = str.Split('@');
                totalSize += long.Parse(arr[1]);
            }
            lbTotSize.Text = DownLoadFile.formatFileSize(totalSize);
        }
        

        public void DoUpgrade()
        {
            DownLoadFile.totalDownLoadBytes = 0;
            //设置processbar最大值
            proBar.Maximum = 100;

            //开始下载
            bool bStatus = true;
            foreach (string str in xmlUtilDown.releaseFileList)
            {
                string[] arr = str.Split('@');
                bStatus=DownLoadFile.DownloadFile(updDir, serverFileDir, arr[0], totalSize, lbProcess, proBar,lbDownLoadSize);
                if (!bStatus)
                {
                    break;
                }
            }
            
            if (!bStatus)
            {
                Util.showErrorMessageBox("下载文件异常，请检查网络或联系厂商");
            }
            else
            {
                //移动文件
                DirectoryInfo folder = new DirectoryInfo(updDir);
                foreach (FileInfo fileInfo in folder.GetFiles())
                {
                    File.Copy(updDir + "\\" + fileInfo.Name, appPath + "\\" + fileInfo.Name,true);
                    File.Delete(updDir + "\\" + fileInfo.Name);
                }
            }

            //启动主程序
            string exeName = appPath + "\\" + xmlUtilDown.applicationStart;
            Process.Start(exeName);

            //关闭下载线程
            Close();
            trd.Abort();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            btnCancel.Enabled = false;
            btnUpdate.Enabled = false;

            trd = new Thread(new ThreadStart(DoUpgrade));
            trd.IsBackground = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            trd.Start();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
